<?php
/**
 * User: 呆呆
 * Agreement: 禁止使用本软件（系统）用于任何违法违规业务或项目,造成的任何法律后果允由使用者（或运营者）承担
 * Date: 2021/3/3
 * Time: 14:34
 */
use app\wenjian\smtp;
use think\facade\Cookie;
use app\wenjian\PayUtils;
use app\wenjian\Pay_Money_Api;

function laqzf($data,$api,$key){//拉起支付
error_reporting(0);
if($data['duijei']==1){//对接模式
$sign = sign($api,$key);
$url = "
        <form id='ckpay' name='ckpay' action='".http_type()."' method='post' target='".(isMobile()==false?'_blank':'_self')."'>
        <input type='hidden' name='pid' value='".$api['pid']."'/>
        <input type='hidden' name='type' value='".$api['type']."'/>
        <input type='hidden' name='record' value='".$api['record']."'/>
        <input type='hidden' name='money' value='".$api['money']."'/>
        <input type='hidden' name='refer' value='".$api['refer']."'/>
        <input type='hidden' name='notify' value='".$api['notify']."'/>
        <input type='hidden' name='mid' value='".$api['mid']."'/>
        <input type='hidden' name='sign' value='".$sign."'/>
        </form>
        <script>document.forms['ckpay'].submit();</script>";
        
}else{
$sign = efaz($api,$key);
$url = "
        <form id='ckpay' name='ckpay' action='".http_type()."/submit.php' method='post' target='".(isMobile()==false?'_blank':'_self')."'>
        <input type='hidden' name='pid' value='".$api['pid']."'/>
        <input type='hidden' name='type' value='".$api['type']."'/>
        <input type='hidden' name='out_trade_no' value='".$api['out_trade_no']."'/>
        <input type='hidden' name='money' value='".$api['money']."'/>
        <input type='hidden' name='return_url' value='".$api['return_url']."'/>
        <input type='hidden' name='notify_url' value='".$api['notify_url']."'/>
        <input type='hidden' name='name' value='".$api['name']."'/>
        <input type='hidden' name='sitename' value='".$api['sitename']."'/>
        <input type='hidden' name='mid' value='".$api['mid']."'/>
        <input type='hidden' name='sign' value='".$sign."'/>
        </form>
        <script>document.forms['ckpay'].submit();</script>";
}
return $url;
}
function Cookie(){//检测Cookie状态||取余额
    $cache = tohc('Cookie');
    if(!$cache->get('Cookie')){
        $cache->set('Cookie',time()+60*3);
    }else{
        if($cache->get('Cookie')){
            if($cache->get('Cookie')<=time()){
                $cache->set('Cookie',time()+60*3);
                $rows = Db::name("pay_gfg")->where("state", 1)->select();
                foreach ($rows as $row){
                    $ree = Db::name("pay_jie")->where("pid", $row['pid'])->where("id",$row['typec_id'])->find();
                    if($ree['game_dm']!='mq_gzfbyjk' and $ree['game_dm']!='mq_gqqyjk'){//云监控(支付宝)||云监控(Q Q)
                         continue;
                    }
                    $pay_money =  new Pay_Money_Api();
                    $json = $pay_money->Get_pay_money($ree['game_dm'],$row['ck']);
                    if($json['code']!=1){
                        Db::name("pay_gfg")->where("pid", $row["pid"])->where("id", $row['id'])->update(array("bug_data"=>$json['money'],"time"=>time(),"land_lx"=>0,"state"=>0));
                        $ds = Db::name("pay_sz")->find();
                        $res = Db::name('pay_user')->where('id',$row["pid"])->find();
                        $sub= $ds['web_name'].'-'.$row['typec_name'].'-Cookie过期通知';
                        $msg = "尊敬的" .$res['user']. "商户<br>  您正在使用的".$row['typec_name']."|MID：" .$row['mid']. "账号Cookie已过期！建议您尽快去".$ds['web_name']."平台更新Cookie，以免影响您的监控收款正常使用。";
                        fmail($res['email'], $sub, $msg);
                    }
                } 
            }
        }
    }
}
function param($id,$param){
    $json = $id;
    $json = json_decode($json,true);
    return base64_decode($json[$param]);
}
function getcookie($head=0){
error_reporting(0);    
if(empty($head)){
return false;
}
$preg = '/Set-Cookie:\ (.*?);/';//获取
preg_match_all($preg,$head,$view);
$v = $view[1];
for($i=0;$i<count($v);$i++){
$string .= $v[$i].';';
}
return $string;
}
//邮箱配置//发送账号，发送通知，发送内容
function fmail($to, $sub, $msg){
        $ds = Db::name("pay_sz")->find();
        if($ds['web_mail']==1){
        $From      = $ds['mail_name'];
        $Host      = $ds['mail_smtp'];
        $Port      = $ds['mail_port'];
        $SMTPAuth  = 1;
        $Username  = $ds['mail_name'];
        $Password  = $ds['mail_pwd'];
        $Nickname  = $ds['web_name'];
        $SSL       = $ds['mail_port'] == 465 ? 1 : 0;
        $msg = msg($sub,$msg);
        $mail      = new SMTP($Host, $Port, $SMTPAuth, $Username, $Password, $SSL);
        $mail->att = array();
        if ($mail->send($to, $From, $sub, $msg, $Nickname)) {
            return true;//邮件发送成功，请注意查收
        } else {
            return false;//对不起，邮件发送失败！请检查邮箱填写是否有误
        }
        }else{
            return false;//邮箱通知关闭状态，请联系客服开启
        }
} 
//生成随机字符串验证码 
function str_rand($codeLen){
 $str="abcdefghijkmnpqrstuvwxyz0123456789ABCDEFGHIGKLMNPQRSTUVWXYZ";    
 $rand="";
 for ($i = 0; $i < $codeLen; $i++) {
  //如：随机数为30 则：$str[30]
  $rand .= $str[mt_rand(0, strlen($str)-1)];
 }
 return $rand;
}
 //检测是否微信内外访问
function is_weixin()
    {
    $ua = $_SERVER['HTTP_USER_AGENT'];
    if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) {
        return true;
        //微信外
    } else {
        return false;
        //微信
    }
}
function tohc($type){//通道缓存
    return cache(array('type'=>'file','expire'=>0,'prefix'=>$type));
}
function CheckSubstrs($substrs,$text){
            foreach($substrs as $substr)
                if(false!==strpos($text,$substr)){
                    return true;
            }
            return false;
}
function isMobile(){//检测是否手机访问
        $useragent=isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
        $useragent_commentsblock=preg_match('|\(.*?\)|',$useragent,$matches)>0?$matches[0]:'';
        
        $mobile_os_list=array('Google Wireless Transcoder','Windows CE','WindowsCE','Symbian','Android','armv6l','armv5','Mobile','CentOS','mowser','AvantGo','Opera Mobi','J2ME/MIDP','Smartphone','Go.Web','Palm','iPAQ');
        $mobile_token_list=array('Profile/MIDP','Configuration/CLDC-','160×160','176×220','240×240','240×320','320×240','UP.Browser','UP.Link','SymbianOS','PalmOS','PocketPC','SonyEricsson','Nokia','BlackBerry','Vodafone','BenQ','Novarra-Vision','Iris','NetFront','HTC_','Xda_','SAMSUNG-SGH','Wapaka','DoCoMo','iPhone','iPod');
        
        $found_mobile=CheckSubstrs($mobile_os_list,$useragent_commentsblock) ||
        CheckSubstrs($mobile_token_list,$useragent);
        
        if ($found_mobile){
            return true;
        }else{
            return false;
        }
} 
function msg($title,$code){//邮箱模板发送内容//发送通知，发送内容
    $conf = Db::name("pay_sz")->find();
    if($conf['mail_email'] == "1"){
        return '<div style="background-color:#ECECEC; padding: 35px;"><table cellpadding="0" align="center"style="width: 600px; margin: 0px auto; text-align: left; position: relative; border-top-left-radius: 5px; border-top-right-radius: 5px; border-bottom-right-radius: 5px; border-bottom-left-radius: 5px; font-size: 14px; font-family:微软雅黑, 黑体; line-height: 1.5; box-shadow: rgb(153, 153, 153) 0px 0px 5px; border-collapse: collapse; background-position: initial initial; background-repeat: initial initial;background:#fff;"><tbody><tr><th valign="middle"
                style="height: 25px; line-height: 25px; padding: 15px 35px; border-bottom-width: 1px; border-bottom-style: solid; border-bottom-color: #42a3d3; background-color: #49bcff; border-top-left-radius: 5px; border-top-right-radius: 5px; border-bottom-right-radius: 0px; border-bottom-left-radius: 0px;"><font face="微软雅黑" size="5" style="color: rgb(255, 255, 255); ">'.$title.' （'.$conf['web_name'].'）</font></th></tr><tr><td><div style="padding:25px 35px 40px; background-color:#fff;"><h2 style="margin: 5px 0px; "><font color="#333333" style="line-height: 20px; "><font style="line-height: 22px; " size="4">'.$code.'</h2><div style="width:700px;margin:0 auto;"><div style="padding:10px 10px 0;border-top:1px solid #ccc;color:#747474;margin-bottom:20px;line-height:1.3em;font-size:12px;">
                            <p>此为系统邮件，请勿回复<br>请保管好您的邮箱，避免账号被他人盗用</p></div></div></div></td></tr></tbody></table></div>';
    }elseif($conf['mail_email'] == "2"){
        return'<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>'.$conf['web_name'].'-邮件通知</title><meta http-equiv="content-type" content="text/html;charset=utf-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"></head><body><div style="width:90%; margin:0 auto; background:#fafafa;margin:50px auto;padding:0px;border:0px;outline:0px;border-radius:6px;max-width:696px;overflow:hidden;"><table cellpadding="0" cellspacing="0" border="0" align="center" width="100%" style=""><tbody><tr bgcolor="#35bdbc" height="80"><td width="580" style="line-height:10px;" align="center"><span style="font-size:24px; color:#ffffff;"></span><br><span style="color:#ffffff; font-size:36px;"><span>'.$title.'</span></span></td></tr></tbody></table>
        &nbsp;&nbsp;<table cellpadding="0" cellspacing="0" border="0" align="center" width="86%" style=""><tbody><tr height="20"></tr><tr><td style=""><img style="margin-right:5px; " src="http://www.jiankongbao.com/img/report/mark.png"><b>操作通知</b></td></tr><tr height="20"></tr></tbody></table><table cellpadding="0" cellspacing="0" border="0" align="center" width="86%" style="background-color: white;"><tbody><tr height="20"></tr><tr><td style="" align="center"><span style="font-size:24px; color:#000;">' . $code . '</span></td></tr><tr height="20"></tr></tbody></table><table width="100%" cellspacing="0" border="0" cellpadding="0" style="background-color: #fafafa;"><tbody><tr><td width="20"></td><td><table width="100%" cellspacing="0" border="0" cellpadding="0"><tbody><tr><td height="20"></td></tr><tr></tr><tr><td height="20"></td></tr></tbody></table></td><td width="20"></td></tr></tbody></table><table width="100%" cellspacing="0" border="0" cellpadding="0" style="background-color: #35bdbc;"><tbody><tr><td width="20"></td><td><table width="100%" cellspacing="0" border="0" cellpadding="0"><tbody><tr><td height="20"></td></tr><tr><td style="font-size:13px;text-align:center;">Copyright &nbsp;© <strong>'.$conf['web_name'].'</strong> 版权所有</td></tr><tr><td height="20"></td></tr></tbody></table></td><td width="20"></td></tr></tbody></table></div></body></html>';
    }elseif($conf['mail_email'] == "3"){
        return '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html lang="en"><head><meta charset="UTF-8"><title>邮件提醒</title><meta name="viewport" content="width=device-width, initial-scale=1.0" /></head><body style="margin: 0; padding: 0;"><table align="center" border="0" cellpadding="0" cellspacing="0" width="90%" style="border-collapse: collapse;"><tr><td><div style="margin: 20px;text-align: center;margin-top: 50px"><h1>'.$title.'</h1></div></td></tr><tr><td><div style="border: #36649d 1px dashed;margin: 30px;padding: 20px"><label style="font-size: 22px;color: #36649d;font-weight: bold">'.$code.'</label></div></td></tr><tr><td><div style="margin: 40px"><p style="color:red;font-size: 14px ">（系统自动发送的邮件，请勿回复。）</p></div></td></tr><tr><td><div align="right" style="margin: 40px;border-top: solid 1px gray" id="bottomTime"><p style="margin-right: 20px"> '.$conf['web_name'].' 团队</p></div></td></tr></table></body></html>';  
    }
}    
function timer($date){//判断还剩多少时间
        $t = strtotime($date)-time();//单位"秒"
        $arr = [];
        $day = intval($t/86400);//天
        $hour = intval((($t/86400)-$day)*24);//小时
        $minute = intval( (((($t/86400)-$day)*24)-$hour)*60 );//分钟
        $second = intval(((((((($t/86400)-$day)*24)-$hour)*60)-$minute)*60));//秒
        return $day.'天'.$hour.'小时'.$minute.'分'.$second.'秒';
    }
function randIP(){//随机IP
    $ip2id= round(rand(600000, 2550000) / 10000); //第一种方法，直接生成
    $ip3id= round(rand(600000, 2550000) / 10000);
    $ip4id= round(rand(600000, 2550000) / 10000);
    //下面是第二种方法，在以下数据中随机抽取
    $arr_1 = array("218","218","66","66","218","218","60","60","202","204","66","66","66","59","61","60","222","221","66","59","60","60","66","218","218","62","63","64","66","66","122","211");
    $randarr= mt_rand(0,count($arr_1)-1);
    $ip1id = $arr_1[$randarr];
    return $ip1id.".".$ip2id.".".$ip3id.".".$ip4id;
}
//取出右边文本
function getbstr($str, $leftStr)
{
    $left = strpos($str, $leftStr);
 return substr($str, $left + strlen($leftStr));
}
//取中间文本
function getSubstr($str, $leftStr, $rightStr)
{
    $left = strpos($str, $leftStr);
    $right = strpos($str, $rightStr,$left);
    if($left < 0 or $right < $left) return '';
    return substr($str, $left + strlen($leftStr), $right-$left-strlen($leftStr));
}
function del0($s)//金额小数点判断   
{   
    $s = trim(strval($s));   
    if (preg_match('#^-?\d+?\.0+$#', $s)) {   
        return preg_replace('#^(-?\d+?)\.0+$#','$1',$s);   
    }    
    if (preg_match('#^-?\d+?\.[0-9]+?0+$#', $s)) {   
        return preg_replace('#^(-?\d+\.[0-9]+?)0+$#','$1',$s);   
    }   
    return $s;   
}
function closeEndOrder(){//检测过期订单
    jiankong();//检测监控状态
    $rows = Db::name("pay_user")->where("active",0)->select();
    foreach ($rows as $res){    
        $closeTime = time()-60*$res['bug_close'];
        $rows = Db::name("pay_order")->where("state",1)->select();
        foreach ($rows as $rew){
            if(date("Y-m-d H:i:s",$rew['create_date'])<=date("Y-m-d H:i:s",$closeTime)){
                Db::name("pay_order")->where("pid",$rew['pid'])->where("order_id",$rew['order_id'])->update(array("state"=>3,"create_time"=>time()));
                $rows = Db::name("pay_order")->where("create_time",time())->select();
                foreach ($rows as $row){
                    Db::name("pay_tmp")->where("pid",$row['pid'])->where("order_id",$row['order_id'])->delete();
                }
                $rows = Db::name("pay_tmp")->select();
                foreach ($rows as $row){
                    $re = Db::name("pay_order")->where("order_id",$row['order_id'])->where("state",1)->find();
                    if (!$re){
                         Db::name("pay_tmp")->where("pid",$row['pid'])->where("order_id",$row['order_id'])->delete();
                    }
                }
            }else{
                $rows = Db::name("pay_tmp")->select();
                foreach ($rows as $row){
                    $re = Db::name("pay_order")->where("order_id",$row['order_id'])->where("state",1)->find();
                    if (!$re){
                         Db::name("pay_tmp")->where("pid",$row['pid'])->where("order_id",$row['order_id'])->delete();
                    }
                }
            }
        }
    }    
}
function huidiao($eer,$row,$data){//推送异步回调数据
if($data['duijei']==1){
$url = api_fssj($eer,$row,$data['key']);
if($eer['method']=='post'){
    $hq = curl_post($row['notify'],$url['notify']);
}else{
    $hq = curl_get($row['notify'].$url['notify']);
}
}else{
$url = api_yizhifu($eer,$row,$data['key']);
if($eer['method']=='post'){
    $hq = curl_post($row['notify'],$url['notify']);
}else{
    $hq = curl_get($row['notify'].$url['notify']);
}
}
return $hq;
}
function qbtdjckg($user)//全部通道-检测开关
{
    $rows = Db::name("pay_qrcode")->select();
    if($rows){
        foreach ($rows as $row){
            $ree = Db::name("pay_qrcode")->where("game_dm",$row['game_dm'])->where("state",0)->select();
            if($ree){
                $re = Db::name("pay_user")->where("user", $user)->find();
                $ree = Db::name("pay_jie")->where("pid", $re['id'])->where("game_dm",$row['game_dm'])->find();
                if(!$ree){
                    $data = array(
                        "pid" => $re['id'],//商户PID
                        "game_dm" => $row['game_dm'],//通道标识
                        "game_img" => $row['game_img'],//通道图标
                        "game_name" => $row['game_name'],//通道名称
                    );
                    Db::name("pay_jie")->insert($data);//通道添加成功
                }
                $ree = Db::name("pay_jie")->where("pid", $re['id'])->where("game_dm",$row['game_dm'])->where("state",1)->find();
                if($ree){
                    Db::name("pay_jie")->where("pid", $re['id'])->where("game_dm", $row['game_dm'])->update(array("state"=>0,"game_img"=>$row['game_img']));//通道禁止使用
                }
            }
            $ree = Db::name("pay_qrcode")->where("game_dm",$row['game_dm'])->where("state",1)->find();
            if($ree){
                $re = Db::name("pay_user")->where("user", $user)->find();
                $ree = Db::name("pay_jie")->where("pid", $re['id'])->where("game_dm",$row['game_dm'])->find();
                if(!$ree){
                    $data = array(
                        "pid" => $re['id'],//商户PID
                        "game_dm" => $row['game_dm'],//通道标识
                        "game_img" => $row['game_img'],//通道图标
                        "game_name" => $row['game_name'],//通道名称
                    );
                    Db::name("pay_jie")->insert($data);//通道添加成功
                }
                $ree = Db::name("pay_jie")->where("pid", $re['id'])->where("game_dm",$row['game_dm'])->where("state",0)->find();
                if($ree){
                    Db::name("pay_jie")->where("pid", $re['id'])->where("game_dm", $row['game_dm'])->update(array("state"=>1,"game_img"=>$row['game_img']));//通道恢复正常
                }
            }
        }
    }  
}
function yecz(){//检测余额充值
    $price = Db::name("pay_price")->where("state", 1)->select();
    if($price){//余额充值
        foreach ($price as $row){
            $re = Db::name("pay_user")->where("user", $row['user'])->find();
            if($re){
                $money = $re['money']+$row['money'];
                Db::name("pay_user")->where("id", $re['id'])->update(array("money"=>$money));//充值余额
                Db::name("pay_price")->where("id", $row["id"])->update(array("state"=>2));//充值到账
            }else{    
                Db::name("pay_price")->where("id", $row["id"])->update(array("state"=>3));//充值不到账：商户不存在
            }
        }
    } 
}
function jiankong(){//检测监控状态
     $rows = Db::name("pay_gfg")->where("jkstate",1)->where("state",1)->select();
     foreach ($rows as $row){
         if ((time()-$row['lastheart'])>360){//6分钟
             Db::name("pay_gfg")->where("pid",$row['pid'])->update(array("jkstate"=>0));
         }
     }
}
function http_type(){//获取当前域名
    $atad = Db::name("pay_sz")->find();
    $http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';
    $url =  ($atad['ds_rul']=='' ? $http_type.$_SERVER['HTTP_HOST']."/":$atad['ds_rul']);//支付网关
    return $url;
}
function success($str){//获取回调结果success
    $words = ['ok', 'success', 'yes', '成功'];//判断是否包含这些字符
    foreach ($words as $word) {
        if (mb_strpos($str, $word) !== false) {
            return true;
        }else{
            continue;
        }
    }
}
function api_fssj($eer,$data,$yek){//默认异步回调数据发送
error_reporting(0);
$dat = array(
		"money"	=> $data['money'],//付款金额
		"order" => $data['order_id'],//云端订单号
		"record"=> $data['record'],//附加参数
);
//建立请求
ksort($dat); //重新排序$dat数组
reset($dat); //内部指针指向数组中的第一个元素
$sign = ''; //初始化需要签名的字符为空
$urls = ''; //初始化URL参数为空
foreach ($dat AS $key => $val) { //遍历需要传递的参数
    if ($val == ''||$key == 'sign') continue; //跳过这些不参数签名
    if ($sign != '') { //后面追加&拼接URL
        $sign .= "&";
        $urls .= "&";
    }
    $sign .= "$key=$val"; //拼接为url参数形式
    $urls .= "$key=" . urlencode($val); //拼接为url参数形式并URL编码参数值
}
$sign = md5($sign .$yek);
if(strpos($data['notify'],'?'))
	$url['notify']='&'.$urls.'&sign='.$sign;
else
    if($eer['method']=='post'){
        $url['notify']= $urls.'&sign='.$sign;
    }else{
        $url['notify']='?'.$urls.'&sign='.$sign;
    }
if(strpos($data['refer'],'?'))
	$url['return']='&'.$urls.'&sign='.$sign;
else
    $url['return']='?'.$urls.'&sign='.$sign;
		
return $url;
}
function api_yizhifu($eer,$data,$key){//易支付异步回调数据发送
if($data['type']=='alipay'){
    $data['type']= 'alipay';
}elseif($data['type']=='weixin'){
    $data['type']= 'wxpay';
}elseif($data['type']=='qq'){
    $data['type']= 'qqpay';
}
    $array=array(
	   'pid'=>$data['pid'],//商户ID
	   'trade_no'=>$data['order_id'],//云端订单号
	   'out_trade_no'=>$data['record'],//商户订单号
	   'type'=>$data['type'],//支付方式
	   'name'=>$data['name'],//商品名称
	   'money'=>$data['money'],//商品金额
	   'trade_status'=>'TRADE_SUCCESS',//支付状态
	);
	$Pay =  new PayUtils();
	$arg = $Pay->argSort($Pay->paraFilter($array));
	$prestr = $Pay->createLinkstring($arg);
	$urlstr = $Pay->createLinkstringUrlencode($arg);
	$sign = $Pay->md5Sign($prestr, $key);
	if(strpos($data['notify'],'?'))
		$url['notify']='&'.$urlstr.'&sign='.$sign.'&sign_type=MD5';
	else
	    if($eer['method']=='post'){
	        $url['notify']= $urlstr.'&sign='.$sign.'&sign_type=MD5';
	    }else{
	        $url['notify']='?'.$urlstr.'&sign='.$sign.'&sign_type=MD5';
	    }
	if(strpos($data['refer'],'?'))
		$url['return']='&'.$urlstr.'&sign='.$sign.'&sign_type=MD5';
	else
	    $url['return']='?'.$urlstr.'&sign='.$sign.'&sign_type=MD5';
		
	return $url;
}
function api_huish($data,$yek){//默认异步回调接收数据
$data = array(
		"money"	=> $data['money'],//付款金额
		"order" => $data['order'],//云端订单号
		"record"=> $data['record'],//附加参数
);
//建立请求
ksort($data); //重新排序$data数组
reset($data); //内部指针指向数组中的第一个元素
$sign = '';//初始化
foreach ($data AS $key => $val) { //遍历GET和POST参数
    if ($val == '' || $key == 'sign') continue; //跳过这些不签名
    if ($sign) $sign .= '&'; //第一个字符串签名不加& 其他加&连接起来参数
    $sign .= "$key=$val"; //拼接为url参数形式
}
$query = md5($sign.$yek); //创建订单所需的参数
return $query;
}
function api_jfjf($data,$key){//易支付异步回调接收数据
$data = array(
    'pid' => $data['pid'],//商户ID
    'trade_no' => $data['trade_no'],//云端订单号
    'out_trade_no' => $data['out_trade_no'],//商户订单号
    'type' => $data['type'],//支付方式
    'name' => $data['name'],//商品名称
    'money' => $data['money'],//商品金额
    'trade_status' => $data['trade_status'],//支付状态
);
$Pay =  new PayUtils();
$arg = $Pay->argSort($Pay->paraFilter($data));
$prestr = $Pay->createLinkstring($arg);
$urlstr = $Pay->createLinkstringUrlencode($arg);
$sign = $Pay->md5Sign($prestr, $key);
return $sign;
}
function sign($api,$yek){//默认接受和发送拉起支付数据签名算法
$data = array(
		"pid" => $api['pid'],//商户ID
		"type" => $api['type'],//支付方式
		"record"=> $api['record'],//附加参数
		"money"	=> $api['money'],//付款金额
		"mid"	=> $api['mid'],//收款账号MID
		"refer" => $api['refer'],//同步回调
		"notify" => $api['notify'],//异步通知
);
ksort($api); //排序GET和POST参数
reset($api); //内部指针指向数组中的第一个元素
$sign = '';//初始化
foreach ($api AS $key => $val) { //遍历附加参数
    if ($val == '' || $key == 'sign') continue; //跳过这些不签名
    if ($sign) $sign .= '&'; //第一个字符串签名不加& 其他加&连接起来参数
    $sign .= "$key=$val"; //拼接为url参数形式
}
return md5($sign .$yek);
}
function efaz($api,$key){//易支付发送拉起支付数据签名算法
$data = array(
	"pid"=>$api['pid'],//商户ID
	"type"=>$api['type'],//支付方式
	"out_trade_no"=>$api['out_trade_no'],//商户订单号
	"money"=>$api['money'],//付款金额
	"return_url"=>$api['return_url'],//同步回调
	"notify_url"=>$api['notify_url'],//异步通知
	"name"=>$api['name'],//商品名称
	"sitename"=>$api['sitename'],//网站名称
);
$Pay =  new PayUtils();
$arg = $Pay->argSort($Pay->paraFilter($data));
$prestr = $Pay->createLinkstring($arg);
$urlstr = $Pay->createLinkstringUrlencode($arg);
$sign = $Pay->md5Sign($prestr, $key);
return $sign;
}
function jfjf($api,$sign,$key){//易支付接受拉起支付数据签名算法
$data = array(
	"pid"=>$api['pid'],//商户ID
	"type"=>$api['type'],//支付方式
	"out_trade_no"=>$api['out_trade_no'],//商户订单号
	"money"=>$api['money'],//付款金额
	"return_url"=>$api['return_url'],//同步回调
	"notify_url"=>$api['notify_url'],//异步通知
	"name"=>$api['name'],//商品名称
	"sitename"=>$api['sitename'],//网站名称
);
$Pay =  new PayUtils();
$arg = $Pay->argSort($Pay->paraFilter($data));
$prestr = $Pay->createLinkstring($arg);
$isSgin = false;
$isSgin = $Pay->md5Verify($prestr,$sign,$key);
return $isSgin;
}
function do_notify($url){
	$ch=curl_init($url);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Linux; U; Android 4.4.1; zh-cn; R815T Build/JOP40D) AppleWebKit/533.1 (KHTML, like Gecko)Version/4.0 MQQBrowser/4.5 Mobile Safari/533.1');
	curl_setopt($ch, CURLOPT_TIMEOUT, 30);
	$return=curl_exec($ch);
	curl_close($ch);
	return $return;
}
function money($money,$data)//手续费算法
{
if($data['type']==1){
    $taocan = Db::name("pay_taocan")->where("id", $data['taocan'])->find();
    if($taocan){
        if($data['taocan_time']>=time()||$data['taocan_time']==0){
            $fee = $taocan['taocan_quanx1'];
        }else{
            Db::name("pay_user")->where("id", $data['id'])->update(array("type"=>0,"taocan"=>0,"taocan_time"=>0));
            $fee = $data['fee'];
        }
    }else{
        Db::name("pay_user")->where("id", $data['id'])->update(array("type"=>0,"taocan"=>0,"taocan_time"=>0));
        $fee = $data['fee'];
    }
}else if($data['type']==2){
    $fee = '0';
}else{
    $fee = $data['fee'];
}  
//$money = 100; // 总金额
//$fee = 5; // 扣除手续费百分之5
$newtotal = ($fee / 100) * $money;
$money = $money - $newtotal;
return $newtotal;
}
function ydzfbqq()//云端-QQ-支付宝
{
    $sz = Db::name("pay_sz")->find();
    $cache = tohc('Heart');
    $rows = Db::name("pay_gfg")->where("state",1)->select();
    foreach ($rows as $row){
        $ros = Db::name("pay_jie")->where("id", $row['typec_id'])->find();
        $data = Db::name("pay_user")->where("id", $row['pid'])->find();
        if($ros['game_dm']!='mq_gzfbyjk' and $ros['game_dm']!='mq_gqqyjk'){//云监控(支付宝)||云监控(Q Q)
            continue;
        }
        $post = array(
            'game_dm' => $ros['game_dm'],//通道标识
            'type' => 'cehsald',//传出类型:支付类型:exec||监控类型:cehsald
            'post' => array(//传出数据
                        'uid' => $row['zhanghao'],//账号UID
                        'ck' => $row['ck'],//账号Cookie
                    )
        );
        if($cache->get('pcyjk')>=date('Y-m-d H:i:s',time())){
        }else{
            $ret = curls($sz['ds_todaorul'],http_build_query($post));
            $json = json_decode($ret,TRUE);
            if($json['code']=="1"){
                $cache = tohc($ros['game_dm']);//通道缓存
                if($cache->get($json['data']['uid'])==$ret){
                        continue;
                }else{
                    $cache->rm($json['data']['uid']);//删除旧缓存
                    $cache->set($json['data']['uid'],$ret,60*$data['bug_close']);// 将数据插入新缓存文件中
                }
            }
        }
    }
}
function jkzfbqq()//云端-QQ-支付宝-监控
{
    $rows = Db::name("pay_order")->where("state", 1)->select();
    foreach ($rows as $row){
        $ree = Db::name("pay_jie")->where("pid", $row['pid'])->where("id",$row['mid_id'])->find();
        if($ree['game_dm']!='mq_gzfbyjk' and $ree['game_dm']!='mq_gqqyjk'){//云监控(支付宝)||云监控(Q Q)
                 continue;
        }
        $cls = app("\\app\common\controller\\".$ree['game_dm']);//支付通道路径
        $run = $cls->cehsald($row);//支付通道数据
        if($run['code']==1){
            $eer = Db::name("pay_gfg")->where("pid", $row['pid'])->where("mid",$row['mid'])->find();
            if($eer){
            $z_pay =  Db::table('pay_order') ->where("pid", $row['pid'])->where("mid", $eer["mid"])->where("state", 2)->sum("price");//总充值
            $jr_pay =  Db::table('pay_order') ->where("pid", $row['pid'])->where("mid", $eer["mid"])->where("state", 2)->whereTime('create_date', 'today')->sum("price");//今日充值
            $zr_pay =  Db::table('pay_order') ->where("pid", $row['pid'])->where("mid", $eer["mid"])->where("state", 2)->whereTime('create_date', 'yesterday')->sum("price");//昨日充值
            Db::name("pay_gfg")->where("pid", $eer["pid"])->where("mid", $eer["mid"])->update(array("z_pay"=>$z_pay,"jr_pay"=>$jr_pay,"zr_pay"=>$zr_pay));
            }
            $data = Db::name("pay_user")->where("id", $row['pid'])->find();
            $hq = huidiao($eer,$row,$data);//推送异步回调数据
            $money = $data['money']-$row['sxf'];
            Db::name("pay_user")->where("id", $data['id'])->update(array("money"=>$money));
            if(success($hq)){
                    Db::name("pay_order")->where("pid", $eer["pid"])->where("id", $row['id'])->update(array("state"=>2,"api_state"=>2,"pay_date"=>time(),"pay_time"=>time()));
            }else{
                    Db::name("pay_order")->where("pid", $eer["pid"])->where("id", $row['id'])->update(array("state"=>2,"api_state"=>3,"pay_date"=>time(),"pay_time"=>time(),"api_jieguo"=>$hq,"api_budan"=>0));
            }
        }
    }
}
function real_ip($type=0){//获取IP
$ip = $_SERVER['REMOTE_ADDR'];
if($type<=0 && isset($_SERVER['HTTP_X_FORWARDED_FOR']) && preg_match_all('#\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}#s', $_SERVER['HTTP_X_FORWARDED_FOR'], $matches)) {
	foreach ($matches[0] AS $xip) {
		if (filter_var($xip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
			$ip = $xip;
			break;
		}
	}
} elseif ($type<=0 && isset($_SERVER['HTTP_CLIENT_IP']) && filter_var($_SERVER['HTTP_CLIENT_IP'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
	$ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif ($type<=1 && isset($_SERVER['HTTP_CF_CONNECTING_IP']) && filter_var($_SERVER['HTTP_CF_CONNECTING_IP'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
	$ip = $_SERVER['HTTP_CF_CONNECTING_IP'];
} elseif ($type<=1 && isset($_SERVER['HTTP_X_REAL_IP']) && filter_var($_SERVER['HTTP_X_REAL_IP'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
	$ip = $_SERVER['HTTP_X_REAL_IP'];
}
return $ip;
}
function checkServerSatatus($ip) {//服务器地址和响应速度
	$str = null;
	$ip = str_replace("http://","",$ip);
	$ip = str_replace("/","",$ip);
	list($usec, $sec) = explode(' ', microtime());  
    $t1 = ((float)$usec + (float)$sec); 
	$fp = @fsockopen($ip,80,$errno,$errstr,10);
	if (!$fp) {
		return array('code'=>0,'msg'=>'不在线[异常]');
	} else {
		fclose($fp);
		list($usec, $sec) = explode(' ', microtime());  
        $t2 = ((float)$usec + (float)$sec); 
		$num= $t2-$t1;
		$mis=$num;
		$mis = round((round(($mis * 1000)/4,3) * 10)/2,3);
		$get_ip_city = get_ip_city($ip);
		$Ping = $mis;
			//if($mis<100)//如果大于800则可能影响速度,所以颜色需要改变
				//$Ping = '<font color=green>'.$mis.'</font>'; //得到连接耗时
			//elseif($mis<150)//如果大于800则可能影响速度,所以颜色需要改变
				//$Ping = '<font color=#ff3399>'.$mis.'</font>'; //得到连接耗时
			//else
				//$Ping = '<font color=red>'.$mis.'</font>'; //得到连接耗时
				
		return array('code'=>1,'msg'=>'在线[正常]','IP'=>$get_ip_city['Result']['IP'],'Country'=>$get_ip_city['Result']['Country'],'Ping'=>$Ping);
	}
}
function DeleteHtml($str){//过滤空格换行 
    $str = trim($str); //清除字符串两边的空格
    $str = preg_replace("/\t/","",$str); //使用正则表达式替换内容，如：空格，换行，并将替换为空。
    $str = preg_replace("/\r\n/","",$str); 
    $str = preg_replace("/\r/","",$str); 
    $str = preg_replace("/\n/","",$str); 
    $str = preg_replace("/ /","",$str);
    $str = preg_replace("/  /","",$str);  //匹配html中的空格
    return trim($str); //返回字符串
}
function get_ip_city($ip=''){//IP地址
    if($ip == ''){
        $ip = real_ip();
    }
    $ip = str_replace("/","",$ip); 
    $ip = str_replace("https:","",$ip); 
    $ip = str_replace("http:","",$ip);
    $url = "http://tool.chinaz.com/AjaxSeo.aspx?t=dns&server=JACYvxRvL1|CnyK9sCL7~g==&id=21577790";
    $data = 'host='.$ip.'&type=1&total=10&process=6&right=0';
    $ret = get_curl($url,$data);
    $ret = getSubstr($ret, '(', ')');
    $json = json_decode($ret,TRUE);
    if($json['state']==1){
    $ip = $json['list'][0]['result'];
    }
	$url = "https://sp1.baidu.com/8aQDcjqpAAV3otqbppnN2DJv/api.php?query={$ip}&co=&resource_id=5809&ie=utf8&oe=gbk&format=json&tn=baidu";
    $ret = get_curl($url);
    $json = json_decode($ret,TRUE);
	$IP_IP = $json['data'][0]['origip'];
	$Country = $json['data'][0]['location'];
	$Result = $Country;
	$Result=array('IP'=>$IP_IP,'Country'=>$Country);
	if(!$IP_IP or !$Country){
		$Result = '无法读取';
		$Result=array('IP'=>'无法读取','Country'=>'无法读取');
	}
	$return=array('code'=>1,'msg'=>'成功','Result'=>$Result);
	return $return;
}
function curls($url,$post_data="",$cookie="",$header=""){//CURL请求
        $ch = curl_init();
        if($header==""){
            $header = [
                'User-Agent:Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1',
            ];
        }
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        // 我们在POST数据哦！
        curl_setopt($ch, CURLOPT_POST, 1);
        // 把post的变量加上
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($ch, CURLOPT_COOKIE, $cookie);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
}
function curl_post($url, $data = array(), $header = array(),$cookie=""){//CURL-POST代理IP请求
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    if(!empty($header)){
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    }
    if($cookie!=""){
        curl_setopt($ch, CURLOPT_COOKIE, $cookie);
    }
    curl_setopt($ch, CURLOPT_POST, 1);
    // 把post的变量加上
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    $output = curl_exec($ch);
    curl_close($ch);
    return $output;
}
function curl_get($url,$header=array(),$cookie=""){//CURL-GET代理IP请求
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    //设置选项，包括URL
    if(!empty($header)){
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    }
    if($cookie!=""){
        curl_setopt($ch, CURLOPT_COOKIE, $cookie);
    }
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15);
    //执行并获取HTML文档内容
    $output = curl_exec($ch);
    //释放curl句柄
    curl_close($ch);
    //打印获得的数据
    return $output;
}
function get_curl2($url,$post=0,$referer=0,$cookie=0,$header=0,$ua=0,$nobaody=0){
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL,$url);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
	$httpheader[] = "Accept:*/*";
	$httpheader[] = "Accept-Encoding:gzip,deflate,sdch";
	$httpheader[] = "Accept-Language:zh-CN,zh;q=0.8";
	$httpheader[] = "Connection:close";
	curl_setopt($ch, CURLOPT_HTTPHEADER, $httpheader);
	curl_setopt($ch, CURLOPT_TIMEOUT, 30);
	if($post){
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
	}
	if($header){
		curl_setopt($ch, CURLOPT_HEADER, TRUE);
	}
	if($cookie){
		curl_setopt($ch, CURLOPT_COOKIE, $cookie);
	}
	if($referer){
		if($referer==1){
			curl_setopt($ch, CURLOPT_REFERER, 'http://m.qzone.com/infocenter?g_f=');
		}else{
			curl_setopt($ch, CURLOPT_REFERER, $referer);
		}
	}
	if($ua){
		curl_setopt($ch, CURLOPT_USERAGENT,$ua);
	}else{
		curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Linux; U; Android 4.4.1; zh-cn; R815T Build/JOP40D) AppleWebKit/533.1 (KHTML, like Gecko)Version/4.0 MQQBrowser/4.5 Mobile Safari/533.1');
	}
	if($nobaody){
		curl_setopt($ch, CURLOPT_NOBODY,1);
	}
	curl_setopt($ch, CURLOPT_ENCODING, "gzip");
	curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
	$ret = curl_exec($ch);
	curl_close($ch);
	return $ret;
}
function get_curl($url,$post=0,$referer=0,$cookie=0,$header=0,$ua=0,$nobaody=0,$ip=0,$split=0){

	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL,$url);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

	$httpheader[] = "Accept:*/*";
	$httpheader[] = "Accept-Encoding:gzip,deflate,sdch";
	$httpheader[] = "Accept-Language:zh-CN,zh;q=0.8";
	$httpheader[] = "Connection:close";
curl_setopt($ch, CURLOPT_HTTPHEADER, $httpheader);

	curl_setopt($ch, CURLOPT_TIMEOUT, 30);
	if($post){
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
	}

	if($header){
		curl_setopt($ch, CURLOPT_HEADER, TRUE);
	}
	if($cookie){
		curl_setopt($ch, CURLOPT_COOKIE, $cookie);
	}
	if($referer){
		if($referer==1){
			curl_setopt($ch, CURLOPT_REFERER, 'http://m.qzone.com/infocenter?g_f=');
		}else{
			curl_setopt($ch, CURLOPT_REFERER, $referer);
		}
	}
if($ip){
   curl_setopt($ch, CURLOPT_HTTPHEADER, array('X-FORWARDED-FOR:'.$ip, 'CLIENT-IP:'.$ip));
}
	if($ua){
		curl_setopt($ch, CURLOPT_USERAGENT,$ua);
	}else{
		curl_setopt($ch, CURLOPT_USERAGENT, 'Stream/1.0.3 (iPhone; iOS 12.4; Scale/2.00)');
	}
	if($nobaody){
		curl_setopt($ch, CURLOPT_NOBODY,1);
	}
	curl_setopt($ch, CURLOPT_ENCODING, "gzip");
	curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
	$ret = curl_exec($ch);
	
	
if ($split) {
			$headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
			$header = substr($ret, 0, $headerSize);
			$body = substr($ret, $headerSize);
			$ret=array();
			$ret['header']=$header;
			$ret['body']=$body;
		} 
curl_close($ch);
return $ret; 
}
function doCurl($url, $data=array(), $header, $timeout=30,$bankId = "",$POST = true){ 
	$ch = curl_init();
	if(substr($url,0,5)=='https'){
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // 从证书中检查SSL加密算法是否存在
		 }
	curl_setopt($ch, CURLOPT_ENCODING, 'gzip,deflate');
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
	curl_setopt($ch, CURLOPT_MAXREDIRS, 2);
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
	curl_setopt($ch, CURLOPT_NOBODY, 1);
	curl_setopt($ch, CURLOPT_POST, $POST);
	curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query($data));
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
	//curl_setopt($ch, CURLOPT_AUTOREFERER, false);
	curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);	 
	$response = curl_exec($ch);
	$info = curl_getinfo($ch);
		
	if($error=curl_error($ch)){
		//die($error);
	}
		//print_R($info);
	curl_close($ch);
	return $bankId  == "alipayDirectPay" ? $info['redirect_url'] : $response;
	 
}